<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    var EventUtil = {
      /**
       * @description: 兼容IE事件绑定
       * @param {*} element DOM元素
       * @param {*} type 事件类型
       * @param {*} handler 事件处理程序
       * @return {*}
       */
      addHandler: function (element, type, handler) {
        if (element.addEventListener) {
          element.addEventListener(type, handler, false);
        } else if (element.attachEvent) {
          element.attachEvent('on' + type, handler);
        } else {
          element['on' + type] = handler;
        }
      },
      /**
       * @description: 返回对 event 对象的引用
       * @param {*} event
       * @return {*}
       */
      getEvent: function (event) {
        return event ? event : window.event;
      },
      /**
       * @description: 返回事件目标
       * @param {*} event
       * @return {*}
       */
      getTarget: function (event) {
        return event.target || event.srcElement;
      },
      /**
       * @description: 阻止事件的默认行为
       * @param {*} event
       * @return {*}
       */
      preventDefault: function (event) {
        if (event.preventDefault) {
          event.preventDefault();
        } else {
          event.returnValue = false;
        }
      },
      removeHandler: function (element, type, handler) {
        if (element.removeEventListener) {
          element.removeEventListener(type, handler, false);
        } else if (element.detachEvent) {
          element.detachEvent('on' + type, handler);
        } else {
          element['on' + type] = null;
        }
      },
      /**
       * @description: 停止事件冒泡，也可能会既停止事件冒泡也停止事件捕获。
       * @param {*} event
       * @return {*}
       */
      stopPropagation: function (event) {
        if (event.stopPropagation) {
          event.stopPropagation();
        } else {
          event.cancelBubble = true;
        }
      },
    };
    /**
     * @description: 方法使用示例
     * @param {*} event
     * @return {*}
     */
    let btn = document.getElementById('myBtn');
    btn.onclick = function (event) {
      event = EventUtil.getEvent(event);
    };
    btn.onclick = function (event) {
      event = EventUtil.getEvent(event);
      let target = EventUtil.getTarget(event);
    };
    let link = document.getElementById('myLink');
    link.onclick = function (event) {
      event = EventUtil.getEvent(event);
      EventUtil.preventDefault(event);
    };
    btn.onclick = function (event) {
      console.log('Clicked');
      event = EventUtil.getEvent(event);
      EventUtil.stopPropagation(event);
    };
    document.body.onclick = function (event) {
      console.log('Body clicked');
    };
  </script>
</html>
